<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-05 11:29
 *
 * Version: 2.0
 */

namespace App\Modules\DataCenter\Services;


use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Models\UserPortfolio;
use App\Modules\Cashier\Repositories\BillRepository;
use App\Modules\DataCenter\Repositories\StatisticsRepository;
use App\Modules\DataCenter\Repositories\VisitHistoryRepository;
use App\Modules\Employee\Controllers\EmployeeController;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Employee\Repositories\PortfolioRepository;
use App\Modules\Employee\Repositories\SalaryRepository;
use App\Modules\Employee\Repositories\UserLikeRepository;
use App\Modules\Inventory\Repositories\GoodsOrderRepository;
use App\Modules\Member\Repositoryies\MemberRepository;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\MemberCard\Services\MemberCardService;
use App\Modules\Order\Repositories\AppointmentRepository;
use App\Modules\Order\Repositories\OrderCommentRepository;
use App\Modules\Order\Repositories\OrderItemRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Repositories\StoreLikeRepository;
use App\Modules\Store\Repositories\StoreRankRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\AmountFlowRepository;
use App\Modules\System\Repositories\PaymentTypeRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use foo\bar;

class StatisticsService extends BaseService
{
	private $visitHistoryRepository;
	private $orderRepository;
	private $appointmentRepository;
	private $memberCardFlowRepository;
	private $goodsOrderRepository;
	private $storeRankRepository;
	private $storeLikeRepository;
	private $memberCardRepository;
	private $portfolioRepository;
	private $orderCommentRepository;
	private $userLikeRepository;
	private $orderItemRepository;
	private $userStoreRepository;
	private $salaryRepository;
	private $employeeRepository;
	private $serviceRepository;
	private $storeRepository;
	private $statisticsRepository;
	private $royaltyRepository;
	private $amountFlowRepository;
	private $paymentTypeRepository;
	private $billRepository;

	public function __construct(VisitHistoryRepository $visitHistoryRepository, OrderRepository $orderRepository, AppointmentRepository $appointmentRepository, MemberCardFlowRepository $memberCardFlowRepository, GoodsOrderRepository $goodsOrderRepository, StoreRankRepository $storeRankRepository, StoreLikeRepository $storeLikeRepository, MemberCardRepository $memberCardRepository, PortfolioRepository $portfolioRepository, OrderCommentRepository $orderCommentRepository, UserLikeRepository $userLikeRepository, OrderItemRepository $orderItemRepository, UserStoreRepository $userStoreRepository, SalaryRepository $salaryRepository, ServiceRepository $serviceRepository, EmployeeRepository $employeeRepository, StoreRepository $storeRepository, StatisticsRepository $statisticsRepository, RoyaltyRepository $royaltyRepository, AmountFlowRepository $amountFlowRepository, PaymentTypeRepository $paymentTypeRepository, BillRepository $billRepository)
	{
		$this->visitHistoryRepository = $visitHistoryRepository;
		$this->appointmentRepository = $appointmentRepository;
		$this->orderRepository = $orderRepository;
		$this->memberCardFlowRepository = $memberCardFlowRepository;
		$this->goodsOrderRepository = $goodsOrderRepository;
		$this->storeRankRepository = $storeRankRepository;
		$this->storeLikeRepository = $storeLikeRepository;
		$this->memberCardRepository = $memberCardRepository;
		$this->portfolioRepository = $portfolioRepository;
		$this->orderCommentRepository = $orderCommentRepository;
		$this->userLikeRepository = $userLikeRepository;
		$this->orderItemRepository = $orderItemRepository;
		$this->userStoreRepository = $userStoreRepository;
		$this->salaryRepository = $salaryRepository;
		$this->employeeRepository = $employeeRepository;
		$this->serviceRepository = $serviceRepository;
		$this->storeRepository = $storeRepository;
		$this->statisticsRepository = $statisticsRepository;
		$this->royaltyRepository = $royaltyRepository;
		$this->amountFlowRepository = $amountFlowRepository;
		$this->paymentTypeRepository = $paymentTypeRepository;
		$this->billRepository = $billRepository;
	}


	public function addVisitor($requestData)
	{
		return $this->visitHistoryRepository->addVisitor($requestData);
	}

	/**
	 * 数据中心头部信息
	 * @param $storeId
	 * @param $userId
	 * @return StoreRepository|StoreRepository[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function getStoreBossHeaderInfo($storeId, $userId)
	{
		$this->userStoreRepository->isStoreBoss($storeId, $userId);
		$storeInfo = $this->storeRepository->findStoreRankByStoreId($storeId);
		// 总订单数
		$storeInfo->total_order_sum = $this->amountFlowRepository->getTodayOrderNum($storeId);
		// 今日总营业额
		$storeInfo->total_amount = $this->amountFlowRepository->getTodayTurnOver($storeId);
		// 总预约数
		$storeInfo->appointment_amount = 100;

		$storeInfo->profit_sum = $this->getTodayProfit($storeId);

		return $storeInfo;
	}


	/**
	 *  收银员的店铺数据总揽
	 */
	public function getStoreDashboard($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return [
			// 今日营收       --->  总营业额
			'store_amount'               => (int)$this->billRepository->orderAmountOrCountsByDate($storeId, 0, $dateList, 1),
			// 订单总数
			'order_counts'               => (int)$this->billRepository->orderAmountOrCountsByDate($storeId, 0, $dateList, 0),
			// 预约数
			'appointment_order_count'    => (int)$this->appointmentRepository->orderCountsByDate($storeId, $dateList),
			// 会员卡 充值/开卡金额
			'member_card_amount'         => (int)$this->billRepository->orderAmountOrCountsByDate($storeId, 0, $dateList, 1, 2),
			// 新增会员数
			'new_member_count'           => (int)$this->memberCardRepository->increaseCountsByStoreAndDate($storeId, $dateList),
			// 会员卡消费金额
			'member_card_service_amount' => (int)$this->memberCardFlowRepository->consumptionAmountsByStoreAndDate($storeId, $dateList)
		];
	}

	/**
	 *
	 */
	public function getMemberSourceData($storeId, $type)
	{
		return [
			'appointmentAndIntoStore' => $this->orderItemRepository->getOrderStatisticsByStoreIdAndField($storeId, 'appointment_id',$type, 'appointment','into_store'),

		'individualAndMember' => $this->orderItemRepository->getOrderStatisticsByStoreIdAndField($storeId, 'member_card_id',$type, 'member_count','individual_count'),

			'sex'=>$this->orderItemRepository->getOrderStatisticsByStoreIdAndField($storeId, 'sex',$type, 'man','woman'),

			'appointOrNoAppoint'  =>$this->orderItemRepository->getOrderStatisticsByStoreIdAndField($storeId, 'is_appoint',$type, 'appoint','no_appoint'),

		];

	}






	/**
	 * 计算店铺的总订单数
	 * @param $storeId
	 * @param int $userId
	 * @return mixed
	 */
//	protected function getTodayOrderNum($storeId, $userId = 0)
//	{
//		return $this->amountFlowRepository->getTodayOrderNum($storeId,$userId);
//		$orderCount = $this->orderRepository->getOrderCount($storeId, $userId, config('constant.orderStatus.done'));
//		$saleCount = $this->goodsOrderRepository->getGoodsSaleCount($storeId, $userId);
//		$memberCardCount = $this->memberCardFlowRepository->getMemberCardSaleCount($storeId, $userId);
//		$total = $orderCount + $saleCount + $memberCardCount;
//	}

	/**
	 * 店长理发师控制台头部信息
	 * @param $storeId
	 * @param $userId
	 * @param $roleType
	 * @return mixed
	 */
	public function getStoreOrBerberControlHeaderInfo($storeId, $userId, $roleType)
	{
		$userId = ($roleType == config('constant.role.barber') || $roleType == config('constant.role.assistant')) ? $userId : 0;
		// 获取理发师今日营业额

		$result['turnOver'] = $this->amountFlowRepository->getTodayTurnOver($storeId, $userId);
		// 获取当前预约的人数
		$result['orderAppointCount'] = $this->orderRepository->getAppointmentCount($storeId, $userId);
		// 获取今日完成订单数
		$result['orderFinishedCount'] = $this->amountFlowRepository->getTodayOrderNum($storeId, $userId);
		return $result;
	}


	/**
	 * 计算店铺或者理发师的营业额
	 * @param $storeId
	 * @param $userId
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-09-11 20:11
	 */
//	public function getTodayTurnOver($storeId, $userId = 0, $dateType = 0)
//	{
//		$dateList = $this->getStartEndDayByDateType($dateType);
//		return $this->amountFlowRepository->getTodayTurnOver($storeId,$userId,$dateList);
//		$orderAmount = $this->orderRepository->getOrderAmount($storeId, $userId, false, $dateList);
//		$saleAmount = $this->goodsOrderRepository->getGoodsSaleAmount($storeId, $userId, $dateList);
//		$memberCardAmount = $this->memberCardFlowRepository->getMemberCardSaleAmount($storeId, $userId, $dateList);
//		$total = round($orderAmount + $memberCardAmount + $saleAmount,2);
//		return $total;
//	}

	/**
	 * 计算店铺的利润
	 * @param $storeId
	 * @param $userId
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-09-11 20:11
	 */
	public function getTodayProfit($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$profit = $this->amountFlowRepository->getProfit($storeId, $dateList);
//		$orderProfit = $this->orderRepository->getOrderAmount($storeId, $userId, true, $dateList);
//		$goodsProfit = $this->goodsOrderRepository->getGoodsProfit($dateList, $storeId, $userId);
//		$cardProfit = $this->memberCardFlowRepository->getCardProfit($dateList, $storeId, $userId);
		$Expenditure = $this->storeRepository->getExpenditure($dateType, $storeId);
		$wage = $this->getStoreWage($dateList, $storeId);
//		$total = round($orderProfit + $goodsProfit + $cardProfit - $Expenditure - $wage,2);
		$total = round($profit - $Expenditure - $wage, 0);
		return $total;
	}


	/**
	 * 获取经营数据
	 */
	public function getOperatingData($storeId)
	{
		$date = date('Y-m-d');
		$compareDate = date('Y-m-d', strtotime($date . ' -1 week'));
		$list = [];
		// 订单数 固定支出 营业额  支出占比=固定支出/营业额
		// 订单数
		$orderServiceData = $this->orderRepository->getAmountRate($storeId, $date, $compareDate);
		// online
		$orderOnlineServiceData = $this->orderRepository->getAmountRate($storeId, $date, $compareDate, true);
		$orderData = $this->amountFlowRepository->getAmountCountRate($storeId, $date, $compareDate);

		$list[] = $this->compareData($orderData, $date, $compareDate, null, 'order_num_rate');
		// 营业额
		// $amountList = $this->storeRankRepository->getAmountRate($storeId, $date, $compareDate);
		$amountList = $this->amountFlowRepository->getAmountRate($storeId, $date, $compareDate);

		$list[] = $this->compareData($amountList, $date, $compareDate, null, 'amount_rate');
		//新增粉丝
		$fansList = $this->storeLikeRepository->getAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($fansList, $date, $compareDate, null, 'fans_rate');
		//访客数
		$visitList = $this->visitHistoryRepository->getAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($visitList, $date, $compareDate, null, 'visit_rate');
		//转化率
		$visitTransList = $this->visitHistoryRepository->getVisitAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($visitList, $date, $compareDate, $visitTransList, 'visit_trans_rate');
		//好评率
		$goodOrderList = $this->orderCommentRepository->getGoodOrderAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($orderOnlineServiceData, $date, $compareDate, $goodOrderList, 'good_order_rate');
		//新增会员
		$newMemberList = $this->memberCardRepository->getAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($newMemberList, $date, $compareDate, null, 'new_member_rate');
		//指定用户占比
		$pointOrderList = $this->orderRepository->getPointAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($orderServiceData, $date, $compareDate, $pointOrderList, 'point_order_rate');

		//新发作品
		$portfolioList = $this->portfolioRepository->getAmountRate($storeId, $date, $compareDate);
		$list[] = $this->compareData($portfolioList, $date, $compareDate, null, 'portfolio_rate');

		//@todo 固定支出
		//@todo 支出占比
		return $list;
	}


	/**
	 * 昨日经营数据处理
	 * @param $list
	 * @param $date
	 * @param $compareDate
	 * @param null $compareList
	 * @param null $filed
	 * @return array
	 * @author Happy dong
	 * @modifiedTime 2019-08-18 22:37
	 */
	public function compareData($list, $date, $compareDate, $compareList = null, $filed = null)
	{
		$result = [
			'title' => isset($filed) ? config('constant.center_data.' . $filed . '.name') : null,
			'count' => 0,
			'rate'  => 0,
			'unit'  => isset($filed) ? config('constant.center_data.' . $filed . '.unit') : null,
			'is_up' => 0 // 0 - 1 down 2 up
		];
		if (!empty($list)) {
			if (isset($compareList)) {
				$list = array_column($list, null, 'dates');
				$compareList = array_column($compareList, null, 'dates');

				$newList = [
					'yesterday_count' => (isset($list[$date]) && isset($compareList[$date])) ? ($list[$date]['counts'] == 0 ? 0 : bcdiv($compareList[$date]['counts'], $list[$date]['counts'], 2) * 100) : 0,
					'compare_count'   => (isset($list[$compareDate]) && isset($compareList[$compareDate])) ? ($list[$compareDate]['counts'] == 0 ? 0 : bcdiv($compareList[$compareDate]['counts'], $list[$compareDate]['counts'], 2) * 100) : 0,
				];
			} else {
				$list = array_column($list, null, 'dates');
				$newList = [
					'yesterday_count' => isset($list[$date]) ? round($list[$date]['counts'], 2) : 0,
					'compare_count'   => isset($list[$compareDate]) ? round($list[$compareDate]['counts'], 2) : 0
				];
			}
			$result['count'] = $newList['yesterday_count'];
			$rate = bcsub($newList['yesterday_count'], $newList['compare_count'], 2);
			$result['rate'] = ($newList['compare_count'] == 0) ? $newList['yesterday_count'] : $rate;

			$result['is_up'] = $result['rate'] > 0 ? 2 : ($result['rate'] < 0 ? 1 : 0);
			$result['rate'] = strval($result['rate']);

//			$result['count'] = $newList['yesterday_count'] < 1 ? round($newList['yesterday_count'] * 100,0) : $newList['yesterday_count'];
		}
		return $result;
	}

	/**
	 * 理发师数据中心 访客数据
	 * @param $storeId
	 * @param int $dateType
	 * @return mixed
	 */
	public function getVisitorData($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);

		$graphList = $this->visitHistoryRepository->getVisitorGraphData($storeId, $dateList['start_date'], $dateList['end_date']);

		$storeIdList = $this->storeRankRepository->getSameLevel($storeId, $dateList['start_date'], $dateList['end_date']);

		$storeIds = (count($storeIdList) == 1) ? $storeIdList[0] : implode(',', $storeIdList);

		$graphListAvg = empty($storeIds) ? [] : $this->visitHistoryRepository->getVisitorGraphData($storeIds, $dateList['start_date'], $dateList['end_date']);

		$result['graph_list'] = $this->graphFormatterData($graphList, $dateList['start_date'], $dateList['end_date'], $graphListAvg, 'visitor', count($storeIdList));

		$result['master'] = max(array_column($result['graph_list'], 'count')) > max(array_column($result['graph_list'], 'avg_count')) ? max(array_column($result['graph_list'], 'count')) : max(array_column($result['graph_list'], 'avg_count'));

		$result['visitor_list'] = $this->visitHistoryRepository->getList($storeId, $dateList['start_date'], $dateList['end_date'], 1);
		return $result;
	}


	/**
	 * 访客列表
	 * @param $storeId
	 * @param int $dateType
	 * @return VisitHistoryRepository[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
	 */
	public function getVisitorList($storeId, $dateType = 0, $pageSize = 10)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->visitHistoryRepository->getList($storeId, $dateList['start_date'], $dateList['end_date'], 0, $pageSize);
		$list = Utilities::dealPage($list);
		return $list;
	}

	/**
	 * 订单数据
	 * @param $storeId
	 * @param int $dateType
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderData($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);

		$OnlineGraphList = $this->orderRepository->getOrderGraphData($storeId, $dateList['start_date'], $dateList['end_date'], true);
		$offlineGraphList = $this->orderRepository->getOrderGraphData($storeId, $dateList['start_date'], $dateList['end_date']);

		$storeIdList = $this->storeRankRepository->getSameLevel($storeId, $dateList['start_date'], $dateList['end_date']);
//
		$storeIds = (count($storeIdList) == 1) ? $storeIdList[0] : implode(',', $storeIdList);
//
		$graphListAvg = empty($storeIds) ? [] : $this->orderRepository->getOrderGraphData($storeIds, $dateList['start_date'], $dateList['end_date']);
//
		$result['graph_list'] = $this->graphFormatterData($OnlineGraphList, $dateList['start_date'], $dateList['end_date'], $graphListAvg, 'order', count($storeIdList), $offlineGraphList);
		$result['order_list'] = $this->orderRepository->getOrderListByDays($storeId, $dateList['start_date'], $dateList['end_date'], true)->toArray();
		return $result;

	}


	/**
	 * 订单数据列表
	 * @param $storeId
	 * @param $pageSize
	 * @param int $dateType
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 * @author Happy dong
	 * @modifiedTime 2019-08-19 15:37
	 */
	public function getOrderList($storeId, $pageSize, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return $this->orderRepository->getOrderListByDays($storeId, $dateList['start_date'], $dateList['end_date'], false, $pageSize);
	}


	/**
	 * 订单数据饼图
	 * @param $storeId
	 * @param int $dateType
	 * @return array
	 * @author Happy dong
	 * @modifiedTime 2019-08-19 16:18
	 */
	public function getPieChartOrderData($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->orderRepository->getPieChartData($storeId, $dateList['start_date'], $dateList['end_date']);
		$result = [
			'online_count'  => empty($list[1]) ? 0 : $list[1]['count'],
			'offline_count' => empty($list[2]) ? 0 : $list[2]['count'],
			'store_count'   => empty($list[3]) ? 0 : $list[3]['count'],
			'card_count'    => empty($list[4]) ? 0 : $list[4]['count'],
			'total_count'   => (empty($list[1]['count']) ? 0 : $list[1]['count']) + (empty($list[2]['count']) ? 0 : $list[2]['count']) + (empty($list[3]['count']) ? 0 : $list[3]['count']) + (empty($list[4]['count']) ? 0 : $list[4]['count'])
		];
		return $result;
	}


	/**
	 * 数据中心 支付方式柱状图
	 * @param $storeId
	 * @param int $dateType
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-08-19 17:07
	 */
	public function getPaymentBarChartList($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return $this->orderRepository->getPaymentBarChartList($storeId, $dateList['start_date'], $dateList['end_date']);
	}


	/**
	 * 数据中心会员卡数据
	 * @param $storeId
	 * @param int $dateType
	 * @return array
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getMemberCardDataCenter($storeId, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$newCount = $this->memberCardRepository->getMemberCardCount($storeId, $dateList['start_date'], $dateList['end_date']);
		$totalCount = $this->memberCardRepository->getMemberCardCount($storeId, null, null, false);
		$list = [
			'new_count'   => empty($newCount) ? 0 : $newCount->card_count,
			'total_count' => empty($totalCount) ? 0 : $totalCount->card_count,
		];

		$list['flow_list'] = $this->memberCardFlowRepository->getFlowList($storeId, $dateList['start_date'], $dateList['end_date'], true)->toArray();
		return $list;
	}


	/**
	 * 数据中心会员卡订单列表数据
	 * @param $storeId
	 * @param $pageSize
	 * @param int $dateType
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 * @author Happy dong
	 * @modifiedTime 2019-08-19 21:27
	 */
	public function getCardFlowList($storeId, $pageSize, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return $this->memberCardFlowRepository->getFlowList($storeId, $dateList['start_date'], $dateList['end_date'], false, $pageSize);
	}


	/**
	 * 指定用户占比数据
	 * @param $storeId
	 * @param int $dateType
	 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[]|\Illuminate\Database\Query\Builder[]|\Illuminate\Support\Collection
	 */
	public function getOrderPointData($storeId, $dateType = 0)
	{

		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->employeeRepository->getOrderPointData($storeId, $dateList['start_date'], $dateList['end_date']);

		foreach ($list as &$v) {
			$v->rate = empty($v->order_count) ? "0%" : (round(($v->appoint_count / $v->order_count) * 100, 0) . '%');
			$v->nick = empty($v->nick) ? $v->username : $v->nick;
			unset($v->username);
		}
		unset($v);

		return $list;
	}


	/**
	 * 指定用户订单列表
	 * @param $storeId
	 * @param $userId
	 * @param int $dateType
	 * @param int $pageSize
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderPointList($storeId, $userId, $dateType = 0, $pageSize = 10)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return $this->orderRepository->getOrderPointList($storeId, $userId, $dateList['start_date'], $dateList['end_date'], $pageSize);
	}


	/**
	 * 理发师排名数据
	 * @param $storeId
	 * @param int $type
	 * @param int $dateType
	 * @return array|mixed
	 */
	public function getBarberRankData($storeId, $type = 1, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = [];
		switch ($type) {
			case config('constant.center.barber.amount'):
				$list = $this->amountFlowRepository->getAmountRankListByBarberId($storeId, $dateList['start_date'], $dateList['end_date']);
				break;
			case config('constant.center.barber.order'):
				$list = $this->amountFlowRepository->getOrderRankListByBarberId($storeId, $dateList['start_date'], $dateList['end_date']);
				break;
			case config('constant.center.barber.portfolio'):
				$list = $this->portfolioRepository->getOrderRankListByBarberId($storeId, $dateList['start_date'], $dateList['end_date']);
				break;
			case config('constant.center.barber.fans'):
				$list = $this->userLikeRepository->getFansRankByBarberId($storeId, $dateList['start_date'], $dateList['end_date']);
				break;
		}
		if (!empty($list)) {
			foreach ($list as &$v) {
				$v = [
					'barber_id'   => $v->barber_id,
					'barber_name' => isset($v->barber_name) ? $v->barber_name : $v->username,
					'counts'      => isset($v->counts) ? $v->counts : 0
				];
			}
			unset($v);
		}
		return $list;

	}


	/**
	 * 服务排名数据
	 * @param $storeId
	 * @param int $dateType
	 * @param int $isAmount
	 * @param int $isLimit
	 * @return mixed
	 */
	public function getOrderServiceData($storeId, $dateType = 0, $isAmount = 1, $isLimit = 1)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		return $this->serviceRepository->getOrderServiceAmountCount($storeId, $dateList['start_date'], $dateList['end_date'], $isAmount, $isLimit);

	}

	/**
	 * 获取订单服务列表
	 * @param $storeId
	 * @param $serviceId
	 * @param $pageSize
	 * @param int $dateType
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderServiceList($storeId, $serviceId, $pageSize, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->orderItemRepository->getOrderServiceList($storeId, $serviceId, $dateList['start_date'], $dateList['end_date'], $pageSize)->toArray();
		if (!empty($list['data'])) {
			$list['data'] = array_map(function ($v) {
				$v['order']['counts'] = $v['count'];
				if (isset($v['order']['user'])) {
					$v['order']['user']['portrait'] = isset($v['order']['user']['picture']['image']) ? $v['order']['user']['picture']['image'] : '';
					if (isset($v['order']['user']['picture']['image'])) {
						unset($v['order']['user']['picture']['image']);
					}
				}
				return $v['order'];
			}, $list['data']);
		}
		return $list;
	}


	/**
	 * 贡献排名
	 * @param $storeId
	 * @param int $dateType
	 * @return array
	 */
	public function getContributionAmount($storeId, $dateType = 0, $isBarber = 1, $isLimt = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		// 计算店铺内 每个理发师的
		if ($isBarber) {
			$result = $this->getContributionBarberData($storeId, $dateList, $isLimt);
		} else {
			//计算店铺内 服务的贡献值
			$result = $this->serviceRepository->getOrderServiceAmountCount($storeId, $dateList['start_date'], $dateList['end_date'], 1, $isLimt, 1);
		}
		return $result;
	}


	/**
	 * 理发师贡献
	 * @param $storeId
	 * @param $dateList
	 * @return array
	 */
	public function getContributionBarberData($storeId, $dateList, $isLimt)
	{
		// 该店铺的所有理发师
		$storeIds = $this->userStoreRepository->getUserListByStoreId($storeId);
		$storeIds = empty($storeIds) ? [] : array_column($storeIds, null, 'uid');
		// 服务订单贡献值
		$orderAmountList = $this->orderRepository->getAmountRankListByBarberIdProfit($storeId, $dateList['start_date'], $dateList['end_date'])->toArray();
		$orderAmountList = empty($orderAmountList) ? [] : array_column($orderAmountList, null, 'barber_id');
		// 办卡订单贡献值
		$cardAmountList = $this->memberCardFlowRepository->getAmountRankListByBarberId($storeId, $dateList['start_date'], $dateList['end_date'])->toArray();
		$cardAmountList = empty($cardAmountList) ? [] : array_column($cardAmountList, null, 'user_id');
		// 商品销售贡献值
		$goodsAmountList = $this->goodsOrderRepository->getAmountRankListByBarberId($storeId, $dateList['start_date'], $dateList['end_date'])->toArray();
		$goodsAmountList = empty($goodsAmountList) ? [] : array_column($goodsAmountList, null, 'user_id');
		// 求和
		$result = [];
		if (!empty($storeIds)) {
			$result = array_map(function ($v) use ($orderAmountList, $cardAmountList, $goodsAmountList) {
				return [
					'counts'   => round((empty($orderAmountList) ? 0 : (isset($orderAmountList[$v['uid']]) ? $orderAmountList[$v['uid']]['counts'] : 0))
						+ (empty($cardAmountList) ? 0 : (isset($cardAmountList[$v['uid']]) ? $cardAmountList[$v['uid']]['counts'] : 0)) + (empty($goodsAmountList) ? 0 : (isset($goodsAmountList[$v['uid']]) ? $goodsAmountList[$v['uid']]['counts'] : 0)), 0),
					'user_id'  => $v['uid'],
					'nick'     => $v['user']['nick'],
					'portrait' => isset($v['user']['picture']) ? $v['user']['picture']['image'] : null
				];
			}, $storeIds);
			$sortCounts = array_column($result, 'counts');
			array_multisort($sortCounts, SORT_DESC, $result);
		}
		$result = ($isLimt && count($result) > 5) ? array_slice($result, 0, 5) : $result;
		return $result;
	}


	/**
	 * 贡献服务列表
	 * @param $storeId
	 * @param $serviceId
	 * @param int $dateType
	 * @param int $pageSize
	 * @return array
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getContributionServiceList($storeId, $serviceId, $dateType = 0, $pageSize = 10)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->orderItemRepository->getOrderServiceList($storeId, $serviceId, $dateList['start_date'], $dateList['end_date'], $pageSize, null, 1)->toArray();
		if (!empty($list['data'])) {
			foreach ($list['data'] as &$v) {
				if (isset($v['order']['user']['picture'])) {
					$v['order']['user']['portrait'] = $v['order']['user']['picture']['image'];
					unset($v['order']['user']['picture']);
				}
				$v['image'] = null;
				if (isset($v['service']['category']['picture'])) {
					$v['image'] = $v['service']['category']['picture']['image'];
					unset($v['service']);
				}
			}
			unset($v);
		}
		$list = Utilities::dealPage($list);
		return $list;
	}

	/**
	 * 理发师贡献列表
	 * @param $storeId
	 * @param $barberId
	 * @param $pageSize
	 * @param int $dateType
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getContributionBarberList($storeId, $barberId, $pageSize, $dateType = 0)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);

//		$list = $this->orderRepository
//			->getOrderServiceList($storeId, $barberId, $dateList['start_date'], $dateList['end_date'], $pageSize, 1)->toArray();
		$list = $this->amountFlowRepository
			->getOrderServiceList($storeId, $barberId, $dateList['start_date'], $dateList['end_date'], $pageSize, 1);
		foreach ($list->Items() as $v) {
			$v->order;
			if ($v->category == 1) {
				empty($v->order->itemsOne->service->category) ?: $v->order->itemsOne->service->category->picture;
			} else if ($v->category == 2) {
				empty($v->order) ?: $v->order->card;
			} else if ($v->category == 3) {
				empty($v->order->goods) ?: $v->order->goods->picture;
			}
		}

//		if (!empty($list['data'])) {
//			foreach ($list['data'] as &$v) {
//				if (isset($v['items'][0]['service']['category']['picture'])) {
//					$v['items'][0]['image'] = $v['items'][0]['service']['category']['picture']['image'];
//					unset($v['items'][0]['service']);
//				}
//			}
//			unset($v);
//		}
		$orderList = Utilities::dealPage($list);
		return $orderList;
	}


	/**
	 * 店长数据中心工资列表
	 * @param $storeId
	 * @return mixed
	 */
	public function getCenterUserSalaryList($storeId, $userId, $month)
	{
		$dates = date('Y-m') == $month ? date('j') : date('t', strtotime($month));
		$startDate = $month . '-' . date('t', strtotime($month));
		$endDate = $month . '-01';
		$list = $this->salaryRepository->getUserSalaryListByStoreId($storeId, $startDate, $endDate, $userId);

		$todayList = $this->orderRepository->storeSalaryList($storeId, date('Y-m-d'));
		$todayList = array_column($todayList, null, 'user_id');

		$list = empty($list) ? [] : array_column($list, null, 'salary_time');
		$monthDay = substr($month, -2);
		$newList = [
			'month'       => $monthDay,
			'base_salary' => 0,
		];
		if (isset($todayList[$userId]) && date('Y-m', $todayList[$userId]['salary_date'] == $month)) {
			$newList['base_salary'] += $todayList[$userId]['amount'];
		}

		$newList['list'] = array_map(function ($v) use ($list, $month, &$newList, $todayList, $userId) {
			$v = $v < 10 ? '0' . $v : $v;
			$newList['base_salary'] += isset($list[$month . '-' . $v]) ? $list[$month . '-' . $v]['amount'] : 0;

			return [
				'date'    => substr($month, -2) . '-' . $v,
				'royalty' => isset($list[$month . '-' . $v]) ? $list[$month . '-' . $v]['royalty'] : ((isset($todayList[$userId]['salary_date']) && date('d', $todayList[$userId]['salary_date']) == $v) ? $todayList[$userId]['royalty'] : 0)
			];

		}, range(1, $dates));
		return $newList;
	}


	/**
	 * 理发师工资数据
	 * @param $storeId
	 * @return mixed
	 */
	public function getCenterUserSalaryData($storeId)
	{
		$dateList = $this->getStartEndDayByDateType(3);
		$list = $this->employeeRepository->getUserSalaryDataByStoreId($storeId, $dateList['start_date'], $dateList['end_date']);
		$todayList = $this->orderRepository->storeSalaryList($storeId, date('Y-m-d'));
		$todayList = array_column($todayList, null, 'user_id');

		foreach ($list as $v) {
			if (!isset($newList[$v->id])) {
				$newList[$v->id] = [
					'id'       => $v->id,
					'nick'     => $v->nick,
					'portrait' => $v->image,
				];
			}
			$vIdSalary = isset($todayList[$v->id]) ? $todayList[$v->id]['amount'] + $todayList[$v->id]['royalty'] : 0;

			if (!isset($newList[$v->id]['total'])) {
				$newList[$v->id]['total'] = 0;
			}
			$newList[$v->id]['total'] += empty($v->amounts) ? 0 : $v->amounts;

			$newList[$v->id]['total'] = round($newList[$v->id]['total'], 2);
			$amounts = $v->amounts;

			if (isset($todayList[$v->id]['salary_date']) && (date('Y-m', $todayList[$v->id]['salary_date']) == $v->months)) {
				$amounts += $vIdSalary;
			}
			isset($v->amounts) ? $newList[$v->id]['list'][] = [
				'amount' => round($amounts, 2),
				'month'  => $v->months
			] : $newList[$v->id]['list'] = [];
		}

		foreach ($newList as &$v) {
			$v['total'] += isset($todayList[$v['id']]) ? $todayList[$v['id']]['amount'] + $todayList[$v['id']]['royalty'] : 0;
		}
		unset($v);

		$amountsList = array_column($newList, 'total');
		array_multisort($amountsList, SORT_DESC, $newList);
		return $newList;
	}


//	public function getTodayStoreSalary($storeId){
//		return $this->orderRepository->storeSalaryList($storeId,date('Y-m-d'));
//	}


	/**
	 * 根据日期类型获取开始和结束日期
	 * @param $dateType
	 * @return mixed
	 */
	public function getStartEndDayByDateType($dateType)
	{
		$dateType = empty($dateType) ? 0 : $dateType;
		$list['start_date'] = config('constant.dataCenter.isToday') ? date('Y-m-d', time()) : date('Y-m-d', strtotime('-1 day'));
		switch ($dateType) {
			case 0:
				$list['end_date'] = $list['start_date'];
				break;
			case 1:
				$list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -6 day'));
				break;
			case 2:
				$list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -29 day'));
				break;
			case 3:
				$list['end_date'] = date('Y-m-d', strtotime($list['start_date'] . ' -1 years'));
				break;
		}
		return $list;
	}


	/**
	 * 格式化访客数据的画图数据
	 * @param $list @线上/其他数据
	 * @param $startDate @开始日期
	 * @param $endDate @结束日期
	 * @param $avgList @平均数据
	 * @param $filed @字段名称
	 * @param int $count @同级店铺数
	 * @param null $offline @线下数据
	 * @return array
	 * @author Happy dong
	 * @modifiedTime 2019-08-19 15:40
	 */
	public function graphFormatterData($list, $startDate, $endDate, $avgList, $filed, $count = 1, $offline = null)
	{
		if ($startDate == $endDate) {
			$resultList = array_map(function ($v) use ($list, $avgList, $count, $offline) {
				$res = [
					'time'      => $v,
					'count'     => empty($list) ? 0 : (isset($list['hour' . $v]) ? $list['hour' . $v] : 0),
					'avg_count' => empty($avgList) ? 0 : (isset($avgList['hour' . $v]) ? round($avgList['hour' . $v] / $count, 0) : 0),
				];
				if (isset($offline)) {
					$res['offline_count'] = isset($offline['hour' . $v]) ? intval($offline['hour' . $v]) : 0;
				}
				return $res;
			}, range(3, 24, 3));
		} else {
			$dateList = [];
			$startDateSeconds = strtotime($startDate);
			$endDateSeconds = strtotime($endDate);
			while ($startDateSeconds >= $endDateSeconds) {
				$dateList[] = date('Y-m-d', $endDateSeconds);
				$endDateSeconds += 86400;
			}
			$list = empty($list) ? [] : array_column($list, null, 'times');
			$resultList = array_map(function ($v) use ($list, $avgList, $filed, $count, $offline) {
				$res = [
					'time'      => substr($v, -5),
					'count'     => empty($list) ? 0 : (isset($list[$v]) ? $list[$v][$filed . '_count'] : 0),
					'avg_count' => empty($avgList) ? 0 : (isset($avgList[$v]) ? round($avgList[$v][$filed . '_count'] / $count, 0) : 0),
				];
				if (isset($offline)) {
					$res['offline_count'] = empty($list) ? 0 : (isset($list[$v]) ? $list[$v][$filed . '_count'] : 0);
				}
				return $res;
			}, $dateList);
		}
		return $resultList;
	}


	/**
	 * 经营数据订单相关
	 * @param $dateType
	 * @param $storeId
	 * @return array
	 * @author Happy dong
	 * @modifiedTime 2019-09-28 16:30
	 */
	public function getStoreBusinessData($dateType, $storeId)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$orderInfo = $this->statisticsRepository->getStoreOrderBusinessData($dateList, $storeId);
		$result = [
			'jx' => [
				'name'   => '剪洗',
				'type'   => 'jx',
				'nums'   => 0,
				'amount' => 0,
				'profit' => 0
			],
			'tr' => [
				'name'   => '烫染',
				'type'   => 'tr',
				'nums'   => 0,
				'amount' => 0,
				'profit' => 0
			],
			'qt' => [
				'name'   => '其他',
				'type'   => 'qt',
				'nums'   => 0,
				'amount' => 0,
				'profit' => 0
			],
			'bk' => [
				'name'   => '办卡',
				'type'   => 'bk',
				'nums'   => 0,
				'amount' => 0,
				'profit' => 0
			],
			'sp' => [
				'name'   => '商品',
				'type'   => 'sp',
				'nums'   => 0,
				'amount' => 0,
				'profit' => 0
			],
		];
		foreach ($orderInfo as $v) {
			switch ($v->type) {
				case 7:
				case 9:
					$result['jx']['nums'] += $v->nums;
					$result['jx']['amount'] += $v->amount;
					$result['jx']['profit'] += $v->profit;
					break;
				case 8:
				case 10:
					$result['tr']['nums'] += $v->nums;
					$result['tr']['amount'] += $v->amount;
					$result['tr']['profit'] += $v->profit;
					break;
				case 11:
					$result['qt']['nums'] += $v->nums;
					$result['qt']['amount'] += $v->amount;
					$result['qt']['profit'] += $v->profit;
					break;
				case 'sp':
					$result['sp']['nums'] += $v->nums;
					$result['sp']['amount'] += $v->amount;
					$result['sp']['profit'] += $v->profit;
					break;
				case 'bk':
					$result['bk']['nums'] += $v->nums;
					$result['bk']['amount'] += $v->amount;
					$result['bk']['profit'] += $v->profit;
					break;
			}
		}
		return array_values($result);
	}


	/**
	 * 经营数据列表
	 * @param $dateType
	 * @param $storeId
	 * @param $type
	 * @param $pageSize
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getStoreBusinessList($dateType, $storeId, $type, $pageSize)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		if ($type == 'sp') {
			$list = $this->goodsOrderRepository->getGoodsSalesList($dateList, $storeId, $pageSize);
		} else if ($type == 'bk') {
			$list = $this->amountFlowRepository->getStoreMemberCardAmountFlowAnalysis($storeId, $dateList, $pageSize);
		} else {
			$list = $this->orderItemRepository->getOrderServiceAmountList($dateList, $storeId, $type, $pageSize);
		}
		$newList = Utilities::dealPage($list);
		return $this->dataFormatStoreBusinessList($newList, $type);
	}


	protected function dataFormatStoreBusinessList($listPage, $type)
	{
		$list = $listPage['items'];
		$result = [];
		if ($type == 'sp') {
			foreach ($list as $v) {
				if (isset($v['items'])) {
					foreach ($v['items'] as $sv) {
						$result[] =
							[
								'image'      => isset($sv['goods']['image']['image']) ? $sv['goods']['image']['image'] : '',
								'title'      => isset($sv['goods']['small_name']) ? $sv['goods']['small_name'] : '',
								'content'    => '',
								'created_at' => $sv['created_at'],
								'amount'     => bcmul($sv['real_price'], $sv['count'], 2),
								'profit'     => bcsub($sv['real_price'], $sv['price'], 2)
								//									$v['real_price'] - $v['buying_sum'] - $v['royalty'],
							];
					}

				}
			}
		} else if ($type == 'bk') {
			$result = array_map(function ($v) {
				$v['content'] = '';
				return $v;
			}, $list);
		} else {
			foreach ($list as $v) {
				if (isset($v['real_price'])) {
					$result[] = [
						'image'      => isset($v['image']) ? $v['image'] : '',
						'title'      => isset($v['nick']) ? $v['nick'] : 'tony',
						'content'    => isset($v['service_name']) ? $v['service_name'] : '',
						'created_at' => is_integer($v['finish_time']) ? date('Y-m-d H:i:s', $v['finish_time']) : $v['finish_time'],
						'amount'     => isset($v['real_price']) ? $v['real_price'] : 0,
						'profit'     => isset($v['profit']) ? $v['profit'] : 0,
					];
				}
			}
		}
		$listPage['items'] = $result;
		return $listPage;
	}

	public function getStoreProfit($dateType, $storeId)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$profit = $this->getTodayProfit($storeId, $dateType);
		$turnOver = $this->amountFlowRepository->getTodayTurnOver($storeId, 0, $dateList);
//		$this->statisticsRepository->getStoreProfit($dateType,$storeId);
		$Expenditure = $this->storeRepository->getExpenditure($dateType, $storeId);
		$wage = $this->getStoreWage($dateList, $storeId);
//		dd($profit,$Expenditure,$wage);
		$cost = $this->amountFlowRepository->getStoreCost($dateList, $storeId);
		$royalty = $this->royaltyRepository->getEmployeeRoyalty($dateList, $storeId);
		return $data = [
			'profit'      => round($profit, 2),      // 今日利润
			'turnover'    => round($turnOver, 2),    // 营业额
			'expenditure' => round($Expenditure, 2), // 固定支出
			'wage'        => round($wage, 2),      // 员工工资
			'royalty'     => round($royalty, 2),     // 员工提成
			'goods_cost'  => round($cost, 2),  // 销售成本
		];
	}

	protected function getStoreWage($dateList, $storeId)
	{
		$employeeCost = $this->userStoreRepository->getSoreEmployeeBaseSalary($storeId);
		if ($dateList['start_date'] != $dateList['end_date']) {
			$baseCost = $this->salaryRepository->getEmployeeCost($dateList, $storeId);
			$employeeCost += isset($baseCost) ? $baseCost : 0;
		} else {
			$employeeCost = $employeeCost / date('t');
		}
		return $employeeCost;
	}

	public function getStorePayment($dateType, $storeId)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$paymentList = $this->paymentTypeRepository->getStorePaymentInfo();
		$list = $this->amountFlowRepository->getStorePaymentInfo($dateList, $storeId);
		foreach ($paymentList as &$v) {
			$v->count = isset($list[$v->payment]) ? $list[$v->payment]['count'] : 0;
			$v->amount = isset($list[$v->payment]) ? $list[$v->payment]['amount'] : 0;
		}
		unset($v);
		return $paymentList;
	}

	/**
	 * 店长端数据中心支付方式列表
	 * @param $dateType
	 * @param $storeId
	 * @param int $payment
	 * @param int $pageSize
	 * @return array
	 */
	public function getStorePaymentList($dateType, $storeId, $payment = 1, $pageSize = 10)
	{
		$dateList = $this->getStartEndDayByDateType($dateType);
		$list = $this->amountFlowRepository->getStorePaymentList($dateList, $storeId, $payment, $pageSize);
		$result = [];
		foreach ($list->items() as $v) {
			$result[] = [
				'image'      => isset($v->user->picture->image) ? $v->user->picture->image : 0,
				'title'      => isset($v->user->nick) ? $v->user->nick : 'tony',
				'content'    => $v->category == 1 ? '服务订单' : $v->category == 2 ? '会员卡订单' : '商品订单',
				'created_at' => $v->created_at->format('Y-m-d H:i:s'),
				'amount'     => $v->real_price,
				'profit'     => ''
			];
		}
		$newList = Utilities::dealPage($list);
		$newList['items'] = $result;
		return $newList;
	}

	/**
	 * 店长端理发师业绩分析
	 * @param $dateType
	 * @param $storeId
	 * @return array
	 */
	public function getStoreAchievement($dateType, $storeId)
	{

		$dateList = $this->getStartEndDayByDateType($dateType);
		$userList = $this->userStoreRepository->getUserListByStoreId($storeId);
		$list = $this->royaltyRepository->getStoreAchievement($dateList, $storeId);
		foreach ($userList as $v) {
			$newList[] = [
				'portrait' => isset($v['user']['picture']['image']) ? $v['user']['picture']['image'] : '',   // 头像
				'count'    => isset($list[$v['uid']]['count']) ? $list[$v['uid']]['count'] : 0,      // 成交单数
				'amount'   => isset($list[$v['uid']]['amount']) ? $list[$v['uid']]['amount'] : 0,
				'user_id'  => $v['uid'],
				'name'     => isset($v['user']['nick']) ? $v['user']['nick'] : ''
			];
		}
		return $newList;
	}
}
